const path = require('path')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const env = process.env.NODE_ENV
const hash = process.env.NODE_ENV === 'development' ? '' : '.[contenthash:8]'
const entry = require('./webpack.entry')()
module.exports = {
  entry: entry,
  watch: env === 'development',
  cache: {
    type: 'filesystem',
    cacheDirectory: path.resolve(__dirname, './node_modules/.cache_temp')
  },
  output: {
    path: path.resolve(__dirname, './public/static'),
    filename: `js/[name].js`
  },
  resolve: {
    extensions: ['.js'],
    mainFiles: ['index'],
    alias: {
      '@': path.resolve('src'),
      'components': path.resolve('public/components'),
    }
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        include: path.resolve(__dirname, './src/js'),
        use: ['babel-loader?cacheDirectory=true']
      },
      {
        test: /\.(css|less)$/,
        use: [
          MiniCssExtractPlugin.loader,
          'css-loader',
          'postcss-loader',
          'less-loader'
        ],
        include: path.resolve(__dirname, './src/css')
      },
      {
        test: /\.(png|svg|jpg|jpeg|gif)$/i,
        type: 'asset',
        parser: {
          dataUrlCondition: {
            maxSize: 8 * 1024
          }
        },
        generator: {
          filename: `img/[name]${hash}[ext]`
        }
      },
      {
        test: /\.(png|svg|jpg|jpeg|gif)$/i,
        use: [
          {
            loader: 'image-webpack-loader',
            options: {
              mozjpeg: {
                progressive: true,
              },
              // optipng.enabled: false will disable optipng
              optipng: {
                enabled: false,
              },
              pngquant: {
                quality: [0.65, 0.90],
                speed: 4
              },
              gifsicle: {
                interlaced: false,
              },
              // the webp option will enable WEBP
              webp: {
                quality: 75
              }
            }
          }
        ]
      },
      {
        test: /\.ejs$/,
        loader: 'ejs-loader',
        include: path.resolve(__dirname, './public/components'),
        options: {
          esModule: false,
          variable: 'qqtData',
        }
      }
    ]
  },
  plugins: [
    new MiniCssExtractPlugin({
      filename: `css/[name].css`,
      chunkFilename: `css/[name].chunk.css`
    }),
    new CleanWebpackPlugin()
  ]
}